import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  Button,
  View,
  Slider,
   TouchableOpacity,
} from 'react-native';
import {Icon,} from 'react-native-elements';
import playbackHelper from './playbackHelper.js';


type Props = {};



export default class FullscreenAudioPlayer extends Component<Props> {

  

  componentWillMount()
    {

      this.setState({
        playPauseButton: playbackHelper.getPlayPauseIcon(),
        songPercentage : 0,
        currentTime : 0,
        currentTimeInSeconds : playbackHelper.displayTwoDigits(0),
        currentTimeInMinutes : playbackHelper.displayTwoDigits(0),
        durationTimeInSeconds : playbackHelper.displayTwoDigits(0),
        durationInMinutes : playbackHelper.displayTwoDigits(0),
        isSliderStop : false,
        repeatButton : playbackHelper.getRepeatIcon(),
        shuffleButtonColor : playbackHelper.getShuffleIcon(),
      });

      
      


    }


  componentDidMount() {
      this.interval = setInterval(() => this.updatePlaybackStatus(), 100);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }


  updatePlaybackStatus()
  {
    this.setState({
      playPauseButton: playbackHelper.getPlayPauseIcon(),   
    });
    if((typeof global.music!== "undefined")&&global.music.isLoaded())
    {
      // console.log('global.playbackObject.currentSongName',global.playbackObject.currentSongName);
      
        global.music.getCurrentTime((seconds) => {
          // console.log('Inside get current time');
          if(global.music.getDuration()>0)
          {
              // console.log('get Duration');
              if(!this.state.isSliderStop)
              {
                // console.log('Slider Change True');
                this.setState(
                {
                  songPercentage: (seconds/global.music.getDuration())*100,
                  currentTime: seconds,
                  currentTimeInMinutes : playbackHelper.displayTwoDigits(Math.floor(seconds/60)),
                  currentTimeInSeconds : playbackHelper.displayTwoDigits(Math.floor(seconds%60)),
                  duration : global.music.getDuration()/60,
                  durationInMinutes : playbackHelper.displayTwoDigits(Math.floor(global.music.getDuration()/60)),
                  durationTimeInSeconds : playbackHelper.displayTwoDigits(Math.floor(global.music.getDuration()%60)),
                });
              }
          }else{
            this.setState(
            {
              songPercentage: 0,
            });
          }
        });
    }
          // console.log(this.state.shuffleButton);

  }


  static navigationOptions = ({navigation}) => {
    return {
      title: "Audio Player View"
    };
  }


  sliderValueChange(value)
  {
    this.state.isSliderStop = true;
    let currentTime = (value * (global.music.getDuration()))/100;
    this.setState(
                {
                  currentTime: currentTime,
                  currentTimeInMinutes : playbackHelper.displayTwoDigits(Math.floor(currentTime/60)),
                  currentTimeInSeconds : playbackHelper.displayTwoDigits(Math.floor(currentTime%60)),
                });
  }

  onSliderChangeComplete(value)
  {
    let currentTime = (value * (global.music.getDuration()))/100;
    console.log('Slider Value:'+value);
    global.music.setCurrentTime(currentTime);
    setTimeout(() => {this.state.isSliderStop = false}, 2);
  }

  playPreviousSong()
  {
    if(this.state.currentTime>2)
    {
      global.music.setCurrentTime(0);
    }else{
      playbackHelper.playPreviousSong();
    }
  }

changeRepeatMode()
  {
    if(++global.playbackObject.currentRepeatMode>2)
    {
      global.playbackObject.currentRepeatMode = 0;
    }
    this.setState({
      repeatButton: playbackHelper.getRepeatIcon(),
    });
  }

changeShuffleMode()
  {
    if(global.playbackObject.isShuffle)
    {
      global.playbackObject.isShuffle = false;
      global.playbackObject.musicCounter = global.playbackObject.indexOftheCurrentSoundTrack;
    }else
    {
      global.playbackObject.isShuffle = true;
    }
    this.setState({
      shuffleButtonColor: playbackHelper.getShuffleIcon(),
    });
  }

  // waitAndStartPlayback()
  // {
  //   setTimeout(() => {this.startPlayback(); }, 2000);
        
  // }

  

  render() {
    // console.log('Rendering');
    
    // console.log("Rendering finished");
    return (
      <View style={styles.audioPlayerContainer}>
        <View style={styles.downArrowIcons}>
           <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
            <Icon name='keyboard-arrow-down' color='#ADADAD' size={50}/>
          </TouchableOpacity>
        </View>
        <View style={styles.playbackInfo}>
          <Text style={styles.playlistNameText}>{global.playbackObject.currentPlaylistName}</Text>
          <View style={styles.songDetailsPanel}>
            <Text style={styles.trackNameText}>{global.playbackObject.currentSongName}</Text>
            <Text style={styles.descriptionText}>{global.playbackObject.currentSoundTrackDescription}</Text>
          </View>
          <View style={styles.sliderPanel}>
            <Slider step={1} maximumValue={100} style={{width: 300}} value = {this.state.songPercentage}
                    onSlidingComplete={this.onSliderChangeComplete.bind(this)} onValueChange={this.sliderValueChange.bind(this)} />
            <View style={styles.timeDisplayPanel}>
              <Text style={styles.displayText}>{this.state.currentTimeInMinutes} : {this.state.currentTimeInSeconds}</Text>
              <Text style={styles.displayText}>{this.state.durationInMinutes} : {this.state.durationTimeInSeconds}</Text>
            </View>
          </View>
        </View>
        <View style={styles.playbackControls}>
            <TouchableOpacity style={styles.playerControlIcons} onPress={() => {this.playPreviousSong()}}>
              <Icon name='skip-previous' color='#8E8E93' size={50}/>
            </TouchableOpacity>
            <TouchableOpacity style={styles.playerControlIcons} onPress={() => {playbackHelper.setCurrentTime(-10)}}>
              <Icon name='fast-rewind' color='#DDDDDD' size={50}/>
            </TouchableOpacity>
            <TouchableOpacity style={styles.playerControlIcons} onPress={() => {playbackHelper.togglePlayPause()}}>
              <Icon name={this.state.playPauseButton} color='#DDDDDD' size={70}/>
            </TouchableOpacity>
            <TouchableOpacity style={styles.playerControlIcons} onPress={() => {playbackHelper.setCurrentTime(10)}}>
              <Icon name='fast-forward' color='#DDDDDD' size={50}/>
            </TouchableOpacity>
             <TouchableOpacity style={styles.playerControlIcons} onPress={() => {playbackHelper.playNextSong()}}>
              <Icon name='skip-next' color='#8E8E93' size={50}/>
            </TouchableOpacity>
        </View>
        <View style={styles.shuffleAndRepeatPanel}>
            <TouchableOpacity style={styles.shuffleAndRepeatIcons} onPress={() => {this.changeRepeatMode()}}>
              <Icon name={this.state.repeatButton} type = 'material-community' color='#DDDDDD' size={50}/>
            </TouchableOpacity>
            <TouchableOpacity style={styles.shuffleAndRepeatIcons} type= 'material-community' onPress={() => {this.changeShuffleMode()}}>
              <Icon name='shuffle' color={this.state.shuffleButtonColor} size={50}/>
            </TouchableOpacity>
        </View>
      </View>
    );
  }
  
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#ffffff',
    alignItems: 'center',
  },
  displayText: {
        color: '#DDDDDD',
        fontWeight: 'bold',
        textAlign: 'right',
        padding: 8,
        fontSize: 20,
        textAlign: 'center',
    },
  trackInfoPanel: {
    flex: 3,
    flexDirection : 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  trackNameText:{
    color: '#fff',
    textAlign: 'left',
    fontSize: 40,
  },
  playlistNameText:{
    color: '#8E8E93',
    textAlign: 'left',
    fontSize: 30,
  },
  descriptionText:{
    color: '#8E8E93',
    textAlign: 'left',
    fontSize: 20,
  },
  playerControlsPanel: {
    flex: 3,
    flexDirection : 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  playerControlIcons: {
    paddingHorizontal: 10,
  },
  audioPlayerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#3C3C3C',
  },
  downArrowIcons: {
    width:350,
    flexDirection:'row',
    paddingVertical: 20,
    justifyContent: 'flex-end',
  },
  playbackInfo: {
    flex: 4,
    flexDirection : 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  songDetailsPanel: {
    flex: 9,
    flexDirection : 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sliderPanel: {
    flex: 3,
    flexDirection : 'column',
    justifyContent: 'space-between',
  },
  timeDisplayPanel: {
    flex: 1,
    flexDirection : 'row',
    justifyContent: 'space-between',
  },
  playbackControls: {
    flex: 1,
    flexDirection : 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  shuffleAndRepeatPanel: {
    flex: 1,
    flexDirection : 'row',
    justifyContent: 'space-between',
  },
  shuffleAndRepeatIcons: {
    paddingHorizontal: 90,
  },
});
